<?php
namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use service\ToolsService;
use think\Db;

/**
 * 前台分类控制器
 *
 * @author leo.lei(346991581@qq.com)
 */
class Category extends BasicAdmin
{

    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'YogaCategory';

    /**
     * 分类列表
     *
     * @return void
     * @author leo.lei(346991581@qq.com)
     */
    public function index()
    {
        $this->title = '分类列表';
        $db = Db::name($this->table)->order('sort asc,id asc');
        $db->where('is_deleted', 0);
        return parent::_list($db, false);
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_data_filter(&$data)
    {
        $typeArr = dict_arr('cate_type');
        foreach ($data as &$vo) {
            $vo['type_txt'] = $typeArr[$vo['type']];
            $vo['ids'] = join(',', ToolsService::getArrSubIds($data, $vo['id']));
        }
        $data = ToolsService::arr2table($data);
    }

    /**
     * 添加
     */
    public function add()
    {
        return $this->_form($this->table, 'form');
    }

    /**
     * 编辑
     */
    public function edit()
    {
        return $this->_form($this->table, 'form');
    }

    /**
     * 表单数据前缀方法
     * @param array $vo
     */
    protected function _form_filter(&$vo)
    {
        if ($this->request->isGet()) {
            // 上级分类处理
            $_menus = Db::name($this->table)->where('status', '1')->order('sort desc,id desc')->select();
            $_menus[] = ['title' => '顶级分类', 'id' => '0', 'pid' => '-1'];
            $menus = ToolsService::arr2table($_menus);
            foreach ($menus as $key => &$menu) {
                if (substr_count($menu['path'], '-') > 3) {
                    unset($menus[$key]);
                    continue;
                }
                if (isset($vo['pid'])) {
                    $current_path = "-{$vo['pid']}-{$vo['id']}";
                    if ($vo['pid'] !== '' && (stripos("{$menu['path']}-", "{$current_path}-") !== false || $menu['path'] === $current_path)) {
                        unset($menus[$key]);
                    }
                }
            }
            $this->assign('menus', $menus);
            $this->assign('types', dict_list('cate_type'));
        }
    }

    /**
     * 删除
     */
    public function del()
    {
        if (DataService::update($this->table)) {
            $this->success("删除成功！", '');
        }
        $this->error("删除失败，请稍候再试！");
    }

    /**
     * 禁用
     */
    public function forbid()
    {
        if (DataService::update($this->table)) {
            $this->success("隐藏成功！", '');
        }
        $this->error("隐藏失败，请稍候再试！");
    }

    /**
     * 启用
     */
    public function resume()
    {
        if (DataService::update($this->table)) {
            $this->success("启用成功！", '');
        }
        $this->error("启用失败，请稍候再试！");
    }
}
